//
// Description: 2. 两数相加
// Created by Loading on 2022/5/1.
//

#include <bits/stdc++.h>
#include <Data_Structure_Definition.h>
#include <Utils.h>

using namespace std;

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    ListNode *head = nullptr;
    ListNode *node = nullptr;
    // 进位
    int carry = 0;
    while (l1 || l2) {
        int x1 = l1 ? l1->val : 0;
        int x2 = l2 ? l2->val : 0;
        if (!head) {
            head = node = new ListNode((x1 + x2 + carry) % 10);
        } else {
            node->next = new ListNode((x1 + x2 + carry) % 10);
            node = node->next;
        }
        carry = (x1 + x2 + carry) / 10;
        if (l1) {
            l1 = l1->next;
        }
        if (l2) {
            l2 = l2->next;
        }
    }
    if (carry) {
        node->next = new ListNode(carry);
    }

    return head;
}

int main() {
    vector<int> nums1{9, 9, 9, 9, 9, 9, 9};
    vector<int> nums2{9, 9, 9, 9};
    auto l1 = generateListNode(nums1);
    auto l2 = generateListNode(nums2);
    auto res = addTwoNumbers(l1, l2);
    cout << printfListNode(res) << endl;

    return 0;
}